package org.jeecg.modules.rental.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.annotation.InterceptorIgnore;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.exception.JeecgBootResultException;
import org.jeecg.common.rental.vo.LoginRentalAccount;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.iot.cache.EBikeCache;
import org.jeecg.modules.rental.entity.*;
import org.jeecg.modules.rental.enums.*;
import org.jeecg.modules.rental.mapper.*;
import org.jeecg.modules.rental.req.RentalEBikeOrderReq;
import org.jeecg.modules.rental.service.IRentalConfigService;
import org.jeecg.modules.rental.service.IRentalOrderService;
import org.jeecg.modules.rental.service.IRentalPackageConfigService;
import org.jeecg.modules.rental.util.OrderSnUtil;
import org.jeecg.modules.iot.api.IControlAPI;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Description: 租赁订单
 * @Author: sean
 * @Date:   2024-06-17
 * @Version: V1.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class RentalOrderServiceImpl extends ServiceImpl<RentalOrderMapper, RentalOrder> implements IRentalOrderService {

    private final RentalEBikeTypeMapper rentalEBikeTypeMapper;

    private final RentalEBikeMapper rentalEBikeMapper;

    private final RentalStoreMapper rentalStoreMapper;

    private final RentalPackageConfigMapper rentalPackageConfigMapper;

    private final RentalAccountPackageMapper rentalAccountPackageMapper;

    private final  RentalAccountCouponMapper rentalAccountCouponMapper;

    private final RentalCouponWriteoffMapper rentalCouponWriteoffMapper;

    private final IRentalPackageConfigService rentalPackageConfigNewService;

    private final IRentalConfigService rentalConfigService;

    private final OrderSnUtil orderSnUtil;

    private final IControlAPI iControlAPI;

    private final EBikeCache vehicleCache;

//    @Autowired
//    private RentalCouponConfigMapper rentalCouponConfigMapper;

//    @Autowired
//    private RentalRecordMapper rentalRecordMapper;

//    @Autowired
//    private BillingStrategyFactory billingStrategyFactory;

//    @Autowired
//    private RentalPackageConfigMapper rentalPackageConfigNewMapper;

//    @Autowired
//    private IRentalAccountCouponService accountCouponService;


    @Transactional
    @Override
    public Result<Boolean> cancellationOrder(String orderId) {
        RentalOrder rentalOrder = baseMapper.selectById(orderId);
        if (rentalOrder==null){
            throw new JeecgBootException("rental.order.service.not.found");
        }
        if(rentalOrder.getOrderStatus()!=1){
            throw new JeecgBootException("rental.order.service.not.unpaid");
        }
        if (rentalOrder.getOrderType() == 3) { // 订单类型 3 表示超时订单
            throw new JeecgBootException("rental.order.service.timeout.cannot.cancel");
        }
        if (rentalOrder.getOrderType() == 4) { // 订单类型 3 表示超时订单
            throw new JeecgBootException("rental.order.service.realtime.cannot.cancel");
        }
        Date date = new Date();
        // 订单改为取消状态
        rentalOrder.setOrderStatus(3);
        rentalOrder.setUpdateTime(date);
        baseMapper.updateById(rentalOrder);
      /*  // 还原优惠券状态
        if (chargeOrder.getAccountCouponId()!=null&&!chargeOrder.getAccountCouponId().equals("")){
            ChargeAccountCoupon chargeAccountCoupon = chargeAccountCouponMapper.selectById(chargeOrder.getAccountCouponId());
            if (chargeAccountCoupon!=null){
                boolean effectiveDate = isEffectiveDate(date, chargeAccountCoupon.getRemainTime());
                if (effectiveDate){
                    chargeAccountCoupon.setWhetherUse(1);
                    chargeAccountCouponMapper.updateById(chargeAccountCoupon);
                }
            }
        }*/
        return  Result.OK(true);
    }

    @Override
    public Page<RentalOrder> orderList(Page page, RentalOrder rentalOrder) {
        QueryWrapper<RentalOrder> queryWrapper = new QueryWrapper<RentalOrder>();
        queryWrapper.eq("account_id", rentalOrder.getAccountId());
        queryWrapper.eq("order_type", rentalOrder.getOrderType());
        if(null != rentalOrder.getOrderType() && 3 == rentalOrder.getOrderType()){
            queryWrapper.eq("order_status", "2");
        }
        Page<RentalOrder> pageList = baseMapper.selectPage(page, queryWrapper);

        // 创建一个 RentalOrderResp 的列表
//        List<RentalOrderResp> rentalOrderRespList = new ArrayList<>();

        if(ObjectUtil.isNotEmpty(pageList.getRecords()) ) {
            List<Long> carTypeIds = pageList.getRecords().stream()
                    .map(RentalOrder::getCarTypeId)
                    .collect(Collectors.toList());
            List<RentalEBikeType> carTypeList = rentalEBikeTypeMapper.selectBatchIds(carTypeIds);
            List<Long> packageConfId = pageList.getRecords().stream()
                    .map(RentalOrder::getPackageConfId)
                    .collect(Collectors.toList());
            List<RentalPackageConfig> rentalPackageConfigList = rentalPackageConfigMapper.selectBatchIds(packageConfId);
            pageList.getRecords().stream().forEach(item -> {
                Optional<RentalEBikeType> typeOptional = carTypeList.stream()
                        .filter(a -> a.getId().equals(item.getCarTypeId()))
                        .findFirst();
                typeOptional.ifPresent(a -> item.setCarImage(a.getCarImage()));

                Optional<RentalPackageConfig> configOptional = rentalPackageConfigList.stream()
                        .filter(a -> a.getId().equals(item.getPackageConfId()))
                        .findFirst();
                configOptional.ifPresent(a -> item.setPackageConfName(a.getPackageName()));

            });
        }
        return pageList;
    }

//    @Override
//    @Transactional
//    public Result<RentalOrder> confirm(ConfirmOrderReq req) {
//        // 获取并校验用户信息
//        RentalPayAccount rentalPayAccount = rentalAccountMapper.selectById(req.getAccountId());
//        if (rentalPayAccount == null) {
//            throw new JeecgBootException("rental.order.service.user.info.fail");
//        }
//
//        //TODO 暂时先不允许，同时存在多个套餐
//        List<RentalAccountPackage> accountPackageList = rentalAccountPackageMapper.effectivePackages(new QueryWrapper<RentalAccountPackage>()
//                .eq("account_id", req.getAccountId()).eq("pkg_status","1"));
//        if (null != accountPackageList && !accountPackageList.isEmpty() && accountPackageList.size() > 0) {
//            throw new RentalVerifyException(VehicleResultCodeEnums.NOT_ALLOWED_RENTAL_MULTIPLE_VEHICLE);
//        }
//        // 初始化订单对象并设置基本信息
//        RentalOrder co = new RentalOrder();
//        RentalEBikeType rentalCarType=new RentalEBikeType();
//        if (4!=req.getOrderType()){
//            // 获取并校验车辆信息
//            List<RentalEBike> rentalCars = rentalEBikeMapper.selectList(new QueryWrapper<RentalEBike>().eq("code", req.getCode()).likeRight("sys_org_code", OrgThreadHolder.get()));
//            if (ObjectUtil.isEmpty(rentalCars) || rentalCars.isEmpty()) {
//                throw new JeecgBootException("rental.order.service.vehicle.info.fail");
//            }
//            RentalEBike rentalCar = rentalCars.get(0);
//            rentalCarType= rentalEBikeTypeMapper.selectById(rentalCar.getCarTypeId());
//            co.setCarTypeId(rentalCar.getCarTypeId());
//            co.setCarId(rentalCar.getId());
//            co.setDepositAmount(rentalCarType.getDepositAmount());
//        }else {
//            RentalEBikeType carType=rentalEBikeTypeMapper.selectById(req.getCarTypeId());
//            co.setCarTypeId(req.getCarTypeId());
//            co.setDepositAmount(carType.getDepositAmount());
//        }
//
////        RentalStore rentalStore = rentalStoreMapper.selectById(rentalCar.getMeshPointId());
//
//        co.setMeshPointId(req.getMeshPointId());
//        co.setAccountId(req.getAccountId());
//
//        co.setPackageConfId(req.getPackageConfId());
//        co.setAccountCouponId(req.getAccountCouponId());
//        co.setOrderType(req.getOrderType());
//
//        co.setDiscountAmount(BigDecimal.ZERO);
//        co.setCount(req.getCount());
//        co.setOrderStatus(1);
//        /*设置支付方式*/
////        co.setPayType(paymentServiceFactory.getPayType(OrgThreadHolder.get()));
//        co.setSysOrgCode(OrgThreadHolder.get());
//
//        //计算套餐金额
//        RentalPackageConfig rentalPackageConfig = rentalPackageConfigMapper.selectById(req.getPackageConfId());
//        PackagesTypeEnums packagesTypeEnums = PackagesTypeEnums.getEnumByValue(rentalPackageConfig.getPackageType());
//        /**
//         * 套餐金额
//         */
//        BigDecimal packageAmount = BigDecimal.ZERO;
//        switch (packagesTypeEnums) {
//            case MINUTE:
////                MinutePackages minutePackages = JsonUtils.toObj(MinutePackages.class, rentalPackageConfig.getPackageConfig());
//                MinutePackages minutePackages = JacksonUtils.toObj(rentalPackageConfig.getPackageConfig(), MinutePackages.class);
//                packageAmount = minutePackages.getPrice().multiply(req.getCount());
//                break;
//            case HOURS:
////                HoursPackages hoursPackages = JsonUtils.toObj(HoursPackages.class, rentalPackageConfig.getPackageConfig());
//                HoursPackages hoursPackages = JacksonUtils.toObj(rentalPackageConfig.getPackageConfig(), HoursPackages.class);
//                packageAmount = hoursPackages.getPrice().multiply(req.getCount());
//                break;
//            case DAILY:
////                DailyPackages dailyPackages = JsonUtils.toObj(DailyPackages.class, rentalPackageConfig.getPackageConfig());
//                DailyPackages dailyPackages = JacksonUtils.toObj(rentalPackageConfig.getPackageConfig(), DailyPackages.class);
//                packageAmount = dailyPackages.getPrice().multiply(req.getCount());
//                break;
//            case MONTH:
////                MonthPackages monthPackages = JsonUtils.toObj(MonthPackages.class, rentalPackageConfig.getPackageConfig());
//                MonthPackages monthPackages = JacksonUtils.toObj(rentalPackageConfig.getPackageConfig(), MonthPackages.class);
//                packageAmount = monthPackages.getPrice().multiply(req.getCount());
//                break;
//            default:
//                System.out.println("Unknown day.");
//                break;
//        }
//        String tradeCode = orderSnUtil.getRentalTradeCode();
//        co.setOrderCode(tradeCode);
//        co.setOrderAmount(packageAmount.add(rentalCarType.getDepositAmount()));
//        co.setDiscountAmount(BigDecimal.ZERO);
//        co.setPayAmount(packageAmount.add(rentalCarType.getDepositAmount()));
//        baseMapper.insert(co);
//        // 返回生成的订单结果
//        return Result.ok(co);
//    }


    @Override
    @Transactional
    public Result<RentalOrder> confirmOrder(RentalEBikeOrderReq req) {
        // 获取并校验用户信息
        LoginRentalAccount rentalAccount = (LoginRentalAccount) SecurityUtils.getSubject().getPrincipal();
        //TODO 暂时先不允许，同时存在多个套餐
        List<RentalAccountPackage> accountPackageList = rentalAccountPackageMapper.effectivePackages(new QueryWrapper<RentalAccountPackage>()
                .eq("account_id", rentalAccount.getId()).eq("pkg_status","1"));
        if (null != accountPackageList && !accountPackageList.isEmpty() && accountPackageList.size() > 0) {
            throw new JeecgBootResultException(EBikeRentalVerifyEnums.NOT_ALLOWED_RENTAL_MULTIPLE_VEHICLE);
        }

        RentalOrder co = new RentalOrder();
        RentalEBikeType carType = new RentalEBikeType();
        Long meshPointId = req.getMeshPointId();
        if (!EBikeOrderTypeEnums.PREBOOK_ORDER.getValue().equals(req.getOrderType().toString()) ){
            // 获取并校验车辆信息
            RentalEBike rentalCar = rentalEBikeMapper
                    .selectOne(new QueryWrapper<RentalEBike>().eq("code", req.getCode()));
            if (ObjectUtil.isEmpty(rentalCar)) {
                throw new JeecgBootException("rental.order.service.vehicle.info.fail");
            }
            meshPointId = rentalCar.getMeshPointId();
            carType= rentalEBikeTypeMapper.selectById(rentalCar.getCarTypeId());
            co.setCarTypeId(rentalCar.getCarTypeId());
            co.setCarId(rentalCar.getId());
            co.setSysOrgCode(rentalCar.getSysOrgCode());
            co.setDepositAmount(carType.getDepositAmount());
        }else {
            RentalStore rentalStore = rentalStoreMapper.selectById(meshPointId);
            co.setSysOrgCode(rentalStore.getSysOrgCode());
            carType = rentalEBikeTypeMapper.selectById(req.getCarTypeId());
            co.setCarTypeId(req.getCarTypeId());
            co.setDepositAmount(carType.getDepositAmount());
        }
        co.setAccountCouponId(req.getAccountCouponId());
        co.setAccountId(rentalAccount.getId().toString());
        co.setPackageConfId(req.getPackageConfId());
        co.setAccountCouponId(req.getAccountCouponId());
        co.setOrderType(req.getOrderType());
        co.setDiscountAmount(req.getDiscountAmount());
        co.setOrderStatus(Integer.parseInt(EBikeOrderStatusEnums.UNPAID.getValue()));
        co.setUseTime(req.getUseTime());
        co.setMeshPointId(meshPointId);
        //计算套餐金额(新的套餐配置)
        RentalPackageConfig packageConfigNew = rentalPackageConfigMapper.selectById(req.getPackageConfId());
        /**
         * 套餐金额
         */
        BigDecimal packageAmount = packageConfigNew.getPrice();
        String tradeCode = orderSnUtil.getRentalTradeCode();
        co.setOrderCode(tradeCode);
        if (carType.getDepositAmount()==null){
            carType.setDepositAmount( BigDecimal.ZERO);
        }
        co.setOrderAmount(packageAmount.add(carType.getDepositAmount()));
        co.setDiscountAmount(BigDecimal.ZERO);
        co.setPayAmount(packageAmount.add(carType.getDepositAmount()));

        /*套餐优惠*/
        if (req.getAccountCouponId() != null) {
            RentalAccountCoupon userCoupon = rentalAccountCouponMapper.selectById(req.getAccountCouponId());
            if (userCoupon == null) {
                return Result.error("rental.order.service.coupon.not.exist");
            }
            // 校验优惠券是否有效
            if (!userCoupon.getStatus().equals("0") || userCoupon.getExpiryDate().isBefore(LocalDate.now())) {
                return Result.error("卡券已过期");
            }
            if (userCoupon.getStatus().equals("1")){
                return Result.error("rental.order.service.coupon.used");
            }
            co.setAccountCouponId(req.getAccountCouponId());
            // 判断优惠券使用门槛
            if (userCoupon.getMinAmount().compareTo(packageAmount) <= 0) {
                // 计算优惠金额
                BigDecimal discountAmount = userCoupon.getFaceValue();

                // 判断优惠金额是否大于支付金额
                if (discountAmount.compareTo(co.getOrderAmount()) >=0) {
                    // 优惠金额大于等于订单金额，订单状态设置为已支付
                    co.setOrderStatus(2);
                    co.setDiscountAmount(co.getOrderAmount()); // 优惠金额等于订单金额
                    co.setPayAmount(BigDecimal.ZERO); // 实付金额为 0
                    co.setPayTime(LocalDateTime.now());
                    baseMapper.insert(co);

                    // 更新用户优惠券状态为已使用
                    userCoupon.setStatus("1");
                    userCoupon.setUseTime(LocalDateTime.now());
                    rentalAccountCouponMapper.updateById(userCoupon);

                    RentalCouponWriteoff writeoff = new RentalCouponWriteoff();
                    writeoff.setAccountCouponId(userCoupon.getId());
                    writeoff.setOrderId(co.getId());
                    writeoff.setUseTime(LocalDateTime.now());
                    writeoff.setDiscAmount(co.getDiscountAmount());
                    writeoff.setStoreId(co.getMeshPointId());
                    writeoff.setSysOrgCode(userCoupon.getSysOrgCode());
                    rentalCouponWriteoffMapper.insert(writeoff);

                    RentalAccountPackage newCap = new RentalAccountPackage();
                    if (req.getOrderType()==1){
                        newCap = createRentalAccountPackage(co, LocalDateTime.now());
                        rentalAccountPackageMapper.insert(newCap);
                    } else if (req.getOrderType()==4){
                        newCap = createRentalAccountPackage(co, req.getUseTime());
                        rentalAccountPackageMapper.insert(newCap);
                    }

                    co.setAccountPackageId(newCap.getId());
                    baseMapper.updateById(co);
                    // 返回订单支付成功结果
                    return new Result(EBikeRentalVerifyEnums.COUPON_ALREADY_USED.getCode(), EBikeRentalVerifyEnums.COUPON_ALREADY_USED.getMessage());
                }

                // 更新用户优惠券状态为已使用
                co.setDiscountAmount(discountAmount);
                co.setPayAmount(co.getOrderAmount().subtract(discountAmount)); // 实付金额 = 订单金额 - 优惠金额
            }
        }
        baseMapper.insert(co);
        // 返回生成的订单结果
        return Result.ok(co);
    }

    @Override
    @Transactional
    public Result<RentalOrder> renewal(RentalEBikeOrderReq req) {
        if (oConvertUtils.isEmpty(req.getAccountPackageId()) || oConvertUtils.isEmpty(req.getPackageConfId()) ){
            return null;
        }
        RentalAccountPackage accountPackage = rentalAccountPackageMapper.selectById(req.getAccountPackageId());
        LocalDateTime endTime = accountPackage.getEndTime();
        RentalPackageConfig configNew=rentalPackageConfigMapper.selectById(req.getPackageConfId());
        /*设置结束时间前4小时内无法续租*/
        LocalDateTime fourHoursBeforeEnd = endTime.minusHours(4);
        if (LocalDateTime.now().isAfter(fourHoursBeforeEnd)) {
            throw new JeecgBootResultException(EBikeRentalVerifyEnums.NOT_RENEWAL_ALLOWED);
        }
        RentalEBikeType rentalCarType = rentalEBikeTypeMapper.selectById(accountPackage.getCarTypeId());
        // 初始化订单对象并设置基本信息
        RentalOrder co = new RentalOrder();
        co.setAccountId(accountPackage.getAccountId());
        co.setCarTypeId(accountPackage.getCarTypeId());
        co.setCarId(accountPackage.getId());
        co.setAccountPackageId(req.getAccountPackageId());
        co.setPackageConfId(configNew.getId());
        co.setAccountCouponId(req.getAccountCouponId());
        co.setOrderType(Integer.parseInt(EBikeOrderTypeEnums.RENEW_ORDER.getValue()));
        co.setDepositAmount(rentalCarType.getDepositAmount());
        co.setDiscountAmount(BigDecimal.ZERO);
        co.setOrderStatus(Integer.parseInt(EBikeOrderStatusEnums.UNPAID.getValue()));
        co.setSysOrgCode(accountPackage.getSysOrgCode());
        // 处理优惠券
        BigDecimal packageAmount = configNew.getPrice();
        String tradeCode = orderSnUtil.getRentalTradeCode();
        co.setOrderCode(tradeCode);
        co.setOrderAmount(packageAmount );
        co.setDiscountAmount(BigDecimal.ZERO);
        co.setPayAmount(packageAmount);
        if (req.getAccountCouponId() != null) {
            co.setAccountCouponId(req.getAccountCouponId());
            RentalAccountCoupon userCoupon = rentalAccountCouponMapper.selectById(req.getAccountCouponId());
            if (userCoupon == null) {
                return Result.error("rental.order.service.coupon.not.exist");
            }
            if (userCoupon.getStatus().equals("1")){
                return Result.error("rental.order.service.coupon.used");
            }
            // 校验优惠券是否有效
            if (!userCoupon.getStatus().equals("0") || userCoupon.getExpiryDate().isBefore(LocalDate.now())) {
                return Result.error("rental.order.service.coupon.expired");
            }

            // 判断优惠券使用门槛
            if (userCoupon.getMinAmount().compareTo(packageAmount) <= 0) {
                // 计算优惠金额
                BigDecimal discountAmount = userCoupon.getFaceValue();

                // 判断优惠金额是否大于支付金额
                if (discountAmount.compareTo(co.getOrderAmount()) >= 0) {
                    // 优惠金额大于等于订单金额，订单状态设置为已支付
                    co.setOrderStatus(2);
                    co.setDiscountAmount(co.getOrderAmount()); // 优惠金额等于订单金额
                    co.setPayAmount(BigDecimal.ZERO); // 实付金额为 0
                    // 更新用户优惠券状态为已使用
                    userCoupon.setStatus("1");
                    co.setPayTime(LocalDateTime.now());
                    userCoupon.setUseTime(LocalDateTime.now());
                    rentalAccountCouponMapper.updateById(userCoupon);
                    RentalPackageConfig packageConfigNew = rentalPackageConfigNewService.getById(co.getPackageConfId());
                    PackagesTypeEnums packageType = PackagesTypeEnums.getEnumByValue(packageConfigNew.getPackageType());
                    LocalDateTime startTime=accountPackage.getEndTime();
                    if (packageConfigNew.getIsRenew()) {
                        switch (packageType) {
                            case MINUTE:
                                endTime = startTime.plusMinutes((long) packageConfigNew.getDuration().doubleValue());
                                break;
                            case HOURS:
                                endTime = startTime.plusHours((long) packageConfigNew.getDuration().doubleValue());
                                break;
                            case DAILY:
                                endTime = startTime.plusDays((long) packageConfigNew.getDuration().doubleValue());
                                break;
                            case MONTH:
                                endTime = startTime.plusMonths((long) packageConfigNew.getDuration().doubleValue());
                                break;
                            default:
                                throw new IllegalArgumentException("Invalid package type: " + packageConfigNew.getPackageType());
                        }
                        accountPackage.setEndTime(endTime);
                        rentalAccountPackageMapper.updateById(accountPackage);
                    }
                    baseMapper.insert(co);
                    return new Result(EBikeRentalVerifyEnums.COUPON_ALREADY_USED.getCode(), EBikeRentalVerifyEnums.COUPON_ALREADY_USED.getMessage());
                } else {
                    // 优惠金额小于订单金额，正常流程
                    co.setDiscountAmount(discountAmount);
                    co.setPayAmount(co.getOrderAmount().subtract(discountAmount)); // 实付金额 = 订单金额 - 优惠金额
                    userCoupon.setUseTime(LocalDateTime.now());
                    rentalAccountCouponMapper.updateById(userCoupon);
                }
            }

        }
        baseMapper.insert(co);
        // 返回生成的订单结果
        return Result.ok(co);
    }

    private RentalAccountPackage createRentalAccountPackage(RentalOrder rentalOrder, LocalDateTime startTime) {
        RentalAccountPackage newCap = new RentalAccountPackage();
        RentalConfig config = rentalConfigService.get(RentalConfigEnums.USEABLE_PACKAGE_CATEGORY.getConfigKey());
        newCap.setPkgCategory(config.getConfigValue());
        newCap.setAccountId(rentalOrder.getAccountId());
        newCap.setCarTypeId(rentalOrder.getCarTypeId());
        newCap.setStartTime(startTime);

        RentalPackageConfig packageConfigNew = rentalPackageConfigNewService.getById(rentalOrder.getPackageConfId());
        PackagesTypeEnums packageType = PackagesTypeEnums.getEnumByValue(packageConfigNew.getPackageType());

        if (packageConfigNew.getIsRental()) {
            LocalDateTime endTime;
            switch (packageType) {
                case MINUTE:
                    endTime = startTime.plusMinutes((long) packageConfigNew.getDuration().doubleValue());
                    break;
                case HOURS:
                    endTime = startTime.plusHours((long) packageConfigNew.getDuration().doubleValue());
                    break;
                case DAILY:
                    endTime = startTime.plusDays((long) packageConfigNew.getDuration().doubleValue());
                    break;
                case MONTH:
                    endTime = startTime.plusMonths((long) packageConfigNew.getDuration().doubleValue());
                    break;
                default:
                    throw new IllegalArgumentException("Invalid package type: " + packageConfigNew.getPackageType());
            }
            newCap.setEndTime(endTime);
        }

        if (rentalOrder.getOrderType() == 1) {
            RentalEBike car = rentalEBikeMapper.selectById(rentalOrder.getCarId());
            RentalStore store = rentalStoreMapper.selectById(car.getMeshPointId());
            newCap.setCarId(car.getId());
            newCap.setMeshPointId(store.getId());
            newCap.setSysOrgCode(car.getSysOrgCode());
            newCap.setLtineraryOrder(orderSnUtil.getRentalOrderSn(store, startTime, newCap.getEndTime()));
        } else if (rentalOrder.getOrderType() == 4) {
            RentalEBikeType carType = rentalEBikeTypeMapper.selectById(rentalOrder.getCarTypeId());
            newCap.setSysOrgCode(carType.getSysOrgCode());
            if (rentalOrder.getMeshPointId() != null) {
                RentalStore store = rentalStoreMapper.selectById(rentalOrder.getMeshPointId());
                newCap.setLtineraryOrder(orderSnUtil.getRentalOrderSn(store, startTime, newCap.getEndTime()));
                newCap.setSysOrgCode(store.getSysOrgCode());
                newCap.setMeshPointId(rentalOrder.getMeshPointId());
            }
        }
        return newCap;
    }



//    @Override
//    @Transactional
//    public Result<RentalOrder> createChargingPileOrder(ChargingPileOrderReq req) {
//        // 获取并校验用户信息
//        RentalPayAccount rentalPayAccount = rentalAccountMapper.selectById(req.getAccountId());
//        if (rentalPayAccount == null) {
//            throw new JeecgBootException("charging.pile.order.service.user.info.fail");
//        }
//        RentalOrder order=new RentalOrder();
//        return Result.ok(order);
//    }



//    @Override
//    @Transactional
//    public Result<RentalOrder> renewal(ConfirmOrderReq req) {
//        if (req.getAccountPackageId()!=null &&req.getPackageConfId()!=null){
//            RentalAccountPackage accountPackage=rentalAccountPackageMapper.selectById(req.getAccountPackageId());
//            LocalDateTime endTime=accountPackage.getEndTime();
//            RentalPackageConfigNew configNew=rentalPackageConfigNewMapper.selectById(req.getPackageConfId());
//
//            RentalEBike car=rentalEBikeMapper.selectById(accountPackage.getCarId());
//            /*设置结束时间前4小时内无法续租*/
//            LocalDateTime fourHoursBeforeEnd = endTime.minusHours(4);
//            if (LocalDateTime.now().isAfter(fourHoursBeforeEnd)) {
//                throw new RentalVerifyException(VehicleResultCodeEnums.NOT_RENEWAL_ALLOWED);
//            }
//            RentalEBikeType rentalCarType = rentalEBikeTypeMapper.selectById(car.getCarTypeId());
//            // 初始化订单对象并设置基本信息
//            RentalOrder co = new RentalOrder();
//            co.setAccountId(accountPackage.getAccountId());
//            co.setCarTypeId(car.getCarTypeId());
//            co.setCarId(car.getId());
//            co.setAccountPackageId(req.getAccountPackageId());
//            co.setPackageConfId(configNew.getId());
//            //co.setAccountCouponId(req.getAccountCouponId());
//            co.setOrderType(2);
//            co.setDepositAmount(rentalCarType.getDepositAmount());
//            co.setDiscountAmount(BigDecimal.ZERO);
//            co.setOrderStatus(1);
//            /*设置支付方式*/
////            co.setPayType(paymentServiceFactory.getPayType(OrgThreadHolder.get()));
//            co.setSysOrgCode(OrgThreadHolder.get());
//            //PackagesTypeEnums packagesTypeEnums = PackagesTypeEnums.getEnumByValue(packageConfigNew.getPackageType());
//            /**
//             * 套餐金额
//             */
//
//            // 处理优惠券
//            BigDecimal packageAmount = configNew.getPrice();
//            String tradeCode = orderSnUtil.getRentalTradeCode();
//            co.setOrderCode(tradeCode);
//            co.setOrderAmount(packageAmount );
//            co.setDiscountAmount(BigDecimal.ZERO);
//            co.setPayAmount(packageAmount);
//            if (req.getAccountCouponId() != null) {
//                co.setAccountCouponId(req.getAccountCouponId());
//                RentalAccountCoupon userCoupon = rentalAccountCouponMapper.selectById(req.getAccountCouponId());
//                if (userCoupon == null) {
//                    return Result.error("rental.order.service.coupon.not.exist");
//                }
//                if ( userCoupon.getStatus().equals("1")){
//                    return Result.error("rental.order.service.coupon.used");
//                }
//                // 校验优惠券是否有效
//                if (!userCoupon.getStatus().equals("0") || userCoupon.getExpiryDate().isBefore(LocalDate.now())) {
//                    return Result.error("rental.order.service.coupon.expired");
//                }
//
//                // 判断优惠券使用门槛
//                if (userCoupon.getMinAmount().compareTo(packageAmount) <= 0) {
//                    // 计算优惠金额
//                    BigDecimal discountAmount = userCoupon.getFaceValue();
//
//                    // 判断优惠金额是否大于支付金额
//                    if (discountAmount.compareTo(co.getOrderAmount()) >= 0) {
//                        // 优惠金额大于等于订单金额，订单状态设置为已支付
//                        co.setOrderStatus(2);
//                        co.setDiscountAmount(co.getOrderAmount()); // 优惠金额等于订单金额
//                        co.setPayAmount(BigDecimal.ZERO); // 实付金额为 0
//                        // 更新用户优惠券状态为已使用
//                        userCoupon.setStatus("1");
//                        co.setPayTime(LocalDateTime.now());
//                        userCoupon.setUseTime(LocalDateTime.now());
//                        rentalAccountCouponMapper.updateById(userCoupon);
//                        RentalPackageConfigNew packageConfigNew = rentalPackageConfigNewService.getById(co.getPackageConfId());
//                        PackagesTypeEnums packageType = PackagesTypeEnums.getEnumByValue(packageConfigNew.getPackageType());
//                        LocalDateTime startTime=accountPackage.getEndTime();
//                        if (packageConfigNew.getIsRenew()) {
//                            switch (packageType) {
//                                case MINUTE:
//                                    endTime = startTime.plusMinutes((long) packageConfigNew.getDuration().doubleValue());
//                                    break;
//                                case HOURS:
//                                    endTime = startTime.plusHours((long) packageConfigNew.getDuration().doubleValue());
//                                    break;
//                                case DAILY:
//                                    endTime = startTime.plusDays((long) packageConfigNew.getDuration().doubleValue());
//                                    break;
//                                case MONTH:
//                                    endTime = startTime.plusMonths((long) packageConfigNew.getDuration().doubleValue());
//                                    break;
//                                default:
//                                    throw new IllegalArgumentException("Invalid package type: " + packageConfigNew.getPackageType());
//                            }
//                            accountPackage.setEndTime(endTime);
//                            rentalAccountPackageMapper.updateById(accountPackage);
//                        }
//                        baseMapper.insert(co);
//                        return new Result(VehicleResultCodeEnums.COUPON_ALREADY_USED.getCode(),VehicleResultCodeEnums.COUPON_ALREADY_USED.getMessage());
//                    } else {
//                        // 优惠金额小于订单金额，正常流程
//                        co.setDiscountAmount(discountAmount);
//                        co.setPayAmount(co.getOrderAmount().subtract(discountAmount)); // 实付金额 = 订单金额 - 优惠金额
//                        userCoupon.setUseTime(LocalDateTime.now());
//                        rentalAccountCouponMapper.updateById(userCoupon);
//                    }
//                }
//
//            }
//            baseMapper.insert(co);
//
//            // 返回生成的订单结果
//            return Result.ok(co);
//
//        }
//        return null;
//    }

    @Override
    public void handleRentalOrder(RentalOrder rentalOrder, LocalDateTime now) {
        RentalEBike car = rentalEBikeMapper.selectById(rentalOrder.getCarId());

        LocalDateTime startTime = now;
        LocalDateTime endTime = rentalPackageConfigNewService.calcPkgEndTime(rentalOrder.getPackageConfId(), startTime);

        RentalAccountPackage newCap = new RentalAccountPackage();
        RentalConfig config = rentalConfigService.get(RentalConfigEnums.USEABLE_PACKAGE_CATEGORY.getConfigKey());
        newCap.setPkgCategory(ObjectUtil.isNotEmpty(config) ? config.getConfigValue() : "1");
        newCap.setAccountId(rentalOrder.getAccountId());
        newCap.setCarId(car.getId());
        newCap.setCarTypeId(car.getCarTypeId());
        if(ObjectUtil.isNotEmpty(car.getMeshPointId())){
            RentalStore store = rentalStoreMapper.selectById(car.getMeshPointId());
            if(ObjectUtil.isNotEmpty(store)){
                newCap.setMeshPointId(store.getId());
                newCap.setLtineraryOrder(orderSnUtil.getRentalOrderSn(store, startTime, endTime));
            }
        }
        newCap.setStartTime(startTime);
        newCap.setEndTime(endTime);
        newCap.setSysOrgCode(car.getSysOrgCode());
        rentalAccountPackageMapper.insert(newCap);
        rentalOrder.setAccountPackageId(newCap.getId());
        baseMapper.updateById(rentalOrder);
        //TODO 电单车开锁，设置租赁标识
        try {
            iControlAPI.openCar(car.getCarCode(),car.getPhone()); // 开车锁
        } catch (Exception e) {
            log.error("{},{}车辆开锁失败:",car.getCarCode(), car.getPlate());
        }
        vehicleCache.setVehicleStatus(car.getCarCode(), "2"); // 设置车辆已租标识
    }

    @Override
    public void handleRenewalOrder(RentalOrder rentalOrder) {
        RentalAccountPackage rentalAccountPackage = rentalAccountPackageMapper.selectById(rentalOrder.getAccountPackageId());
        LocalDateTime endTime = rentalPackageConfigNewService.calcPkgEndTime(rentalOrder.getPackageConfId(), rentalAccountPackage.getEndTime());
        rentalAccountPackage.setEndTime(endTime);
        rentalAccountPackageMapper.updateById(rentalAccountPackage);
    }

    @Override
    public void handleOvertimeOrder(RentalOrder rentalOrder) {
        RentalEBike car = rentalEBikeMapper.selectById(rentalOrder.getCarId());
        if (car != null) {
            // 计算超时费用等逻辑
            // TODO 电单车关锁
//            iControlAPI.closeCar(car.getCarCode(),car.getPhone());
        }
    }

    @Override
    public void handleReservationOrder(RentalOrder rentalOrder, LocalDateTime now) {
        RentalEBikeType carType = rentalEBikeTypeMapper.selectById(rentalOrder.getCarTypeId());
        RentalStore store = rentalStoreMapper.selectById(rentalOrder.getMeshPointId());
        RentalConfig config = rentalConfigService.get(RentalConfigEnums.USEABLE_PACKAGE_CATEGORY.getConfigKey());

        LocalDateTime startTime = rentalOrder.getUseTime();
        LocalDateTime endTime = rentalPackageConfigNewService.calcPkgEndTime(rentalOrder.getPackageConfId(), startTime);

        RentalAccountPackage newCap = new RentalAccountPackage();
        newCap.setPkgCategory(config.getConfigValue());
        newCap.setAccountId(rentalOrder.getAccountId());
        newCap.setCarTypeId(carType.getId());
        newCap.setStartTime(startTime);
        newCap.setEndTime(endTime);
        newCap.setLtineraryOrder(orderSnUtil.getRentalOrderSn(store, now, endTime));
        newCap.setMeshPointId(store.getId());
        newCap.setSysOrgCode(store.getSysOrgCode());
        rentalAccountPackageMapper.insert(newCap);

        rentalOrder.setAccountPackageId(newCap.getId());
        baseMapper.updateById(rentalOrder);
    }


}
